package com.coldchain.auth.module.client.service.impl;

import com.coldchain.auth.module.client.bean.ClientInfo;
import com.coldchain.auth.module.client.entity.Client;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.coldchain.auth.jwt.client.ClientTokenUtil;
import com.coldchain.auth.module.client.mapper.ClientMapper;
import com.coldchain.auth.module.client.service.IAuthClientService;
import com.coldchain.common.exception.auth.ClientInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * @ClassName IAuthClientServiceImpl

 * @Author fangliai
 * @Date 2018/8/29 9:19
 * @Vesion 1
**/
@Service
public class IAuthClientServiceImpl  implements IAuthClientService {
    private static final Logger log= LoggerFactory.getLogger(IAuthClientServiceImpl.class);
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ClientTokenUtil clientTokenUtil;



    @Override
    public String apply(String clientId, String secret) throws Exception {
      Client client=getClient(clientId,secret);
      return clientTokenUtil.generateToken(new ClientInfo(client.getCode(),client.getName(),client.getId()));
    }


    @Override
    public List<String> getAllowedClient(String clientId, String secret)throws  Exception {
        Client info = this.getClient(clientId, secret);
        List<String> clients = clientMapper.selectAllowedClient(info.getId() + "");
        if(clients==null) {
            new ArrayList<String>();
        }
        return clients;
    }


    @Override
    public List<String> getAllowedClient(String serviceId) throws Exception {
        Client info = getClient(serviceId);
        List<String> clients = clientMapper.selectAllowedClient(info.getId() + "");
        if(clients==null) {
            new ArrayList<String>();
        }
        return clients;
    }


    @Override
    public void validate(String clientId, String secret) throws Exception {
        Client client = getClient(clientId);
        if(!client.getSecret().equals(secret)){
            log.error("client secret invalid error by clientId[{}]",clientId);
            throw new ClientInvalidException("client secret invalid error");
        }
    }

    /**
     * 获取客户端实例
     * @param clientId  客户端id(code)
     * @param secret  客户端密钥
     * @return
     * @throws Exception
     */
    private Client getClient(String clientId, String secret)throws Exception{
        Client client=null;
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq(true,"code",clientId)
                    .eq("secret",secret);

        try{
            client=clientMapper.selectOne(queryWrapper);
        }catch (Exception e){
            throw new Exception(String.format("find  db error by clientId[%s] and secret[%s]",clientId,secret));
        }
        if(client==null){
            throw new Exception(String.format("not find clientId:%s,check  clinet secret is %s",clientId,secret));
        }
        return  client;
    }

    private Client getClient(String clientId) throws Exception{
        Client client=null;
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("code",clientId);
        try{
            client=clientMapper.selectOne(queryWrapper);
        }catch (Exception e){
            throw new Exception(String.format("find  db error by clientId[%s]",clientId));
        }
        if(client==null){
            throw new Exception(String.format("not find clientId:%s",clientId));
        }
        return  client;
    }
}
